// /userManage/userOptions
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable} from '@ant-design/pro-components';
import { Button, Space, Tag, Image, Switch, message,Modal,Select } from 'antd';
import type { SelectProps } from 'antd';
import { useRef,useState,useEffect } from 'react';
import { getUserList,editUserApi,createUserApi,delUserApi,getRoleListApi } from '@/service/index'
import type{ UserList,CreateUserParams,UpdateUserParams } from '@/service/type';
import FormCom  from './components/FormCom'
import style from './UserList2.module.scss';
import { useSelector } from 'react-redux'
import type{ RootState } from '@/store'



function UserList2() {
  const [addUser, setAddUser] = useState(false);
  const [editUser, setEditUser] = useState(false);
  const [showRole, setShowRole] = useState(false);
  const actionRef = useRef<ActionType>(null);
  const [pageSize, setPageSize] = useState(5);
  const [list, setList] = useState<SelectProps['options']>([]);
  const [defaultRole, setDefaultRole] = useState<string[]>([]);
  const [initVal, setInitVal] = useState<{ username: string; password: string; status: number,confirm:string,id:string,email:string } | null>(null)
  const [currentId, setCurrentId] = useState<string>('')
  const [currentRole, setCurrentRole] = useState<string[]>([])
  const [userList, setUserList] = useState<UserList[]>([])

  useEffect(() => {
    getRoleList();
  },[])

  const onAddUser = async (params:CreateUserParams) => {
    try {
      const res = await createUserApi(params)
      if(res.data.code === 0){
        message.success('创建成功')
        actionRef.current?.reload()
        setAddUser(false) 
      }
    } catch (e) {
      console.log(e) 
    }
  }

  const onEditUser = async (params:UpdateUserParams) => {
    try {
      const res = await editUserApi(params)
      if(res.data.code === 0){
        message.success('编辑成功')
        actionRef.current?.reload()
        setEditUser(false) 
      } else {
        message.error(res.data.msg)
      }
    } catch (e) {
      console.log(e) 
    }
  }

  const onDelUser = async (id:string) => {
    try {
      const res = await delUserApi(id) 
      if(res.data.code === 0){
        message.success('删除成功')
        actionRef.current?.reload() 
      } else {
        message.error(res.data.msg) 
      }
    } catch (e) {
      console.log(e)
    }
  }

  const getRoleList = async () => {
    try {
      const res = await getRoleListApi()
      if(res.data.code === 0){
        // setRoleList(res.data.data.list)
        const arr = [...res.data.data.list]
        const newArr =arr.map(item=>
          {
            return {
              label: item.name,
              value: item._id,
              key: item._id,
              id: item._id
            }
          }
        )
        setList(newArr)
        console.log(newArr)
      } else {
        message.error(res.data.msg) 
      }
    } catch (e) {
      console.log(e) 
    }
  }

  const onRole = () => {
    onEditUser({
      id:currentId,//??
      roles:currentRole
    })
    setShowRole(false)
  };

  const columns: ProColumns<UserList>[] = [
    {
      title: '头像',
      dataIndex: 'avatar',
      search:false,
      valueType: 'image',
      ellipsis: true,
      render: (_, record) => {
        return record.avatar ? (
          <Image
            width={50}
            height={50}
            src={record.avatar}
            alt="Avatar"
          />
        )
        : (
          <Tag color="blue">{record.username}</Tag> 
        )
      }
  
    },
    {
      title: '用户名',
      dataIndex: 'username',
      ellipsis: true,
      valueType: 'text'
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: { text: '禁用' },
        1: { text: '启用' }
      },
      render: (_, record) => {
        const changeStatus = async (newStatus: number) => {
          try {
            const res = await editUserApi({
              id:record._id,
              status:newStatus,
              password:record.password,
              username:record.username
            })
            if(res.data.code === 0){
              message.success('状态更新成功')
              actionRef.current?.reload()
            } else {
              message.error(res.data.msg)
            }
          } catch (e) {
            console.log(e)
          }
        };
        return (
          <Switch
            checked={record.status === 1}
            onChange={(checked) => changeStatus(checked ? 1 : 0)}
          />
        );
      }
    },
    {
      title: '密码',
      dataIndex: 'password',
      valueType: 'text',
      search: false
    },
    {
      title: '邮箱',
      search: false,
      dataIndex: 'email',
      valueType: 'text'
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      valueType: 'text',
      search: false,
      render: (_, record) => {
        // const creatorInfo = userList.find(user => user._id === record.creator);
        // return creatorInfo ? creatorInfo.username : '-';
        return record.creator?.username
      }
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'createdAt',
      valueType: 'dateTime'
    },
    {
      title: '最后登录时间',
      search: false,
      dataIndex: 'lastLoginTime',
      valueType: 'dateTime'
    },
    {
      title: '登录次数',
      search: false,
      dataIndex: 'loginCount',
      valueType: 'text'
    },
    {
      fixed: 'right',
      title: '操作',
      key: 'action',
      search: false,
      width: 250,
      render: (text, record, _, action) => {
        const getEdit = () => {
          setInitVal({
            username: record.username,
            email: record.email,
            password: record.password,
            status: record.status,
            confirm: record.password,
            id: record._id
          });
          setEditUser(true);
        };
        return (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                setCurrentId(record._id);
                // 初始化角色
                if (Array.isArray(record.roles)) {
                  const defaultRoleValues = record.roles.map(role => {
                    return {
                      label: role.name,
                      value: role._id,
                      key: role._id,
                      id: role._id
                    }
                  });
                  setDefaultRole(defaultRoleValues);
                } else {
                  setDefaultRole([]);
                }
                setShowRole(true);
              }}
            >
              分配角色
            </Button>
            <Button size="small" onClick={() => getEdit()}>
              编辑用户
            </Button>
            <Button
              type="primary"
              danger
              size="small"
              onClick={() => onDelUser(record._id)}
            >
              删除
            </Button>
          </Space>
        );
      }
    }
  ];

  return (
    <div>
      <ProTable<UserList>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params, sort, filter) => {
          const { current, pageSize, ...otherParams } = params;
          const res = await getUserList({
            page: current!,
            pagesize: pageSize!,
            ...otherParams,
          });
          setUserList(res.data.data.list)
          return {
            data: res.data.data.list,
            success: true,
            total: res.data.data.total,
          };
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'sessionStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        rowKey="_id"
        search={{
          labelWidth: 'auto',
        }}
        form={{
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: pageSize,
          onShowSizeChange: (page, pageSize) => setPageSize(pageSize),
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setAddUser(true)
            }}
            type="primary"
          >
            创建用户
          </Button>
        ]}
      />
      {
        addUser && (
          <div className={style.formbox}>
            <FormCom 
              onShow={setAddUser}
              submit={onAddUser}
            />
          </div> 
        )
      }
      {
        editUser && (
          <div className={style.formbox}>
            <FormCom 
              onShow={setEditUser}
              initValue={initVal!}
              submit={onEditUser}
            />
          </div> 
        )
      }
      <Modal
        title="分配角色"
        open={showRole}
        onOk={() => onRole()}
        onCancel={() => setShowRole(false)}
      >
        <Select
          mode="multiple"
          allowClear
          style={{ width: '100%' }}
          placeholder="Please select"
          value={defaultRole}
          options={list}
          onChange={(selectedValues) => {
            const newArr = [...selectedValues]
            setCurrentRole(newArr)
            setDefaultRole(newArr)
          }} 
        />
      </Modal>
    </div>
  );
}


export default UserList2;